package com.huluobo.sign.pages

import android.text.TextUtils
import android.util.Log
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.UIState
import com.huluobo.lib_http.Const
import com.huluobo.sign.SignIntent
import com.huluobo.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/7/28.
 */
//地图的View
lateinit var mapView: MapView

//高德地图本体
lateinit var map: AMap

//定位展示器
lateinit var myLocationStyle: MyLocationStyle

//地理位置信息检索
lateinit var geocodeSearch: GeocodeSearch

//解析地理位置
lateinit var query: RegeocodeQuery

//计时器
lateinit var timer: Timer

@Composable
fun SignCommitPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {

    //上班打卡的字符串
    var startTime by remember {
        mutableStateOf("上班还未打卡")
    }

    //下班打卡的字符串
    var endTime by remember {
        mutableStateOf("下班还未打卡")
    }

    //打卡按钮文字
    var btnName by remember {
        mutableStateOf("上班打卡")
    }

    //按钮上的时间
    var nowTime by remember {
        mutableStateOf("00:00:00")
    }

    //控制按钮是否可以被点击,如果上下班都打完卡,当日不可点击
    var enable by remember {
        mutableStateOf(true)
    }

    //存取上下班的时间
    val kv = MMKV.defaultMMKV()

    var lat by remember {
        mutableStateOf(0.0)
    }

    var lon by remember {
        mutableStateOf(0.0)
    }

    var type by remember {
        mutableStateOf("")
    }

    var address by remember {
        mutableStateOf("")
    }

    var status by remember {
        mutableStateOf("")
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            timer = Timer()
            timer.schedule(timerTask {
                nowTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            }, 0, 1000)
        }

        //处理初始化时上下班打卡的逻辑
        launch {
            val signTime = kv.decodeString(Const.PARAM_SIGN_IN, "").toString()
            if (!TextUtils.isEmpty(signTime)) {
                //如果不为空,判断是否是今天打卡
                val time = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                val statusIn = kv.decodeString(Const.PARAM_STATUS_IN).toString()
                //2025-07-30 14:46:00
                val signDate = signTime.substring(0, 10)
                //判断日期是否是今天
                if (time == signDate) {
                    //今天打过卡
                    startTime = "上班时间 : $signTime $statusIn"
                    btnName = "下班打卡"
                    val outTime = kv.decodeString(Const.PARAM_SIGN_OUT, "").toString()
                    if (!TextUtils.isEmpty(outTime)) {
                        val statusOut = kv.decodeString(Const.PARAM_STATUS_OUT).toString()
                        //如果下班打卡不为空,截取日期对比是否是今天
                        val outDate = outTime.substring(0, 10)
                        if (time == outDate) {
                            //如果是今天
                            endTime = "下班时间 : $outTime $statusOut"
                            //按钮不可点
                            enable = false
                        }
                    }
                } else {
                    //如果今天未打卡,修改按钮为默认
                    btnName = "上班打卡"
                }
            }
        }

        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        ToastUtils.showLong("添加签到/签退信息失败")
                        Log.e("TagA", "添加签到/签退信息失败")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        ToastUtils.showLong("添加签到/签退信息成功")
                        navHostController.popBackStack()
                    }
                }
            }
        }
    })

    Column(
        Modifier.padding(10.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        BaseTitle(title = "签到/签退", navHostController = navHostController)

        AndroidView(factory = {
            //展示地图布局
            mapView = MapView(it)
            //创建地图
            mapView.onCreate(null)
            //获取地图对象,通过mapView来获取
            map = mapView.map
            //new出地图定位器
            myLocationStyle = MyLocationStyle()
            //设置刷新时间
            myLocationStyle.interval(2000)
            //给地图对象赋值定位器
            map.myLocationStyle = myLocationStyle
            //打开定位器开关
            map.isMyLocationEnabled = true

            map.addOnMyLocationChangeListener { location ->
                //实例化地理位置信息检索
                geocodeSearch = GeocodeSearch(BaseApp.context)
                //实例化解析地理位置,需要传递一个经纬度的点,扫描时间,解析类型
                query = RegeocodeQuery(LatLonPoint(location.latitude, location.longitude), 2000f, GeocodeSearch.AMAP)
                geocodeSearch.getFromLocationAsyn(query)
                geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(result: RegeocodeResult?, error: Int) {
                        address = result?.regeocodeAddress?.formatAddress.toString()
                        lon = location.longitude
                        lat = location.latitude
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                    }
                })
            }

            mapView
        }, modifier = Modifier.height(300.dp))

        Spacer(modifier = Modifier.height(50.dp))
        Text(
            text = startTime, modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(10.dp))
        Text(
            text = endTime, modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )

        Button(
            onClick = {
                val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                val workStart = "08:00:00"
                val workEnd = "17:00:00"
                if (btnName == "上班打卡") {
                    kv.encode(Const.PARAM_SIGN_IN, time)
                    status = if (time.substring(11, time.length) > workStart) "迟到" else "正常"
                    kv.encode(Const.PARAM_STATUS_IN, status)
                    startTime = "上班时间 : $time $status"
                    btnName = "下班打卡"
                    type = "上班"
                } else {
                    kv.encode(Const.PARAM_SIGN_OUT, time)
                    status = if (time.substring(11, time.length) < workEnd) "早退" else "正常"
                    kv.encode(Const.PARAM_STATUS_OUT, status)
                    endTime = "下班时间 : $time $status"
                    enable = false
                    type = "下班"
                }

                val map = mapOf(
                    Const.PARAM_LAT to lat,
                    Const.PARAM_LON to lon,
                    Const.PARAM_ADDRESS to address,
                    Const.PARAM_TYPE to type,
                    Const.PARAM_STATUS to status,
                )
                vm.sendIntent(SignIntent.AddSign(map))
            }, modifier = Modifier
                .size(140.dp)
                .clip(CircleShape), enabled = enable
        ) {
            Column {
                Text(text = btnName, fontSize = 22.sp)
                Text(text = nowTime, fontSize = 22.sp)
            }
        }

        Button(onClick = {
            kv.remove(Const.PARAM_SIGN_IN)
            kv.remove(Const.PARAM_SIGN_OUT)
            kv.remove(Const.PARAM_STATUS_IN)
            kv.remove(Const.PARAM_STATUS_OUT)
        }) {
            Text(text = "清空kv")
        }
    }

    //当page销毁的时候会调用
    DisposableEffect(Unit) {
        onDispose {
            //销毁地图,阻止定位消耗流量
            mapView.onDestroy()
        }
    }
}